import { createRouter, createWebHashHistory } from "vue-router"
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import AppLayout from '@/layout/AppLayout.vue'
import { store } from "@/store"
import goods from "./modules/goods"

const routes = [
  {
    path: '/',
    name: 'AppLayout',
    component: AppLayout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('@/views/home/index.vue'),
        meta: { title: '首页', requiresAuth: true },
      },
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/user/userList.vue'),
        meta: { title: '用户列表', requiresAuth: true }
      },
      {
        path: '/roles',
        name: 'Roles',
        component: () => import('@/views/roles/rolesList.vue'),
        meta: { title: '角色列表', requiresAuth: true }
      },
      {
        path: '/rights',
        name: 'Rights',
        component: () => import('@/views/rights/rightsList.vue'),
        meta: { title: '权限列表', requiresAuth: true }
      },
      goods,
      {
        path: '/params',
        name: 'GoodsParams',
        component: () => import('@/views/param/paramsList.vue'),
        meta: { title: '参数列表' }
      },
      {
        path: '/categories',
        name: 'Categories_List',
        component: () => import('@/views/categories/categoriesList.vue'),
        meta: { title: '商品分类' }
      },
      {
        path: '/orders',
        name: 'Orders_List',
        component: () => import('@/views/orders/ordersList.vue'),
        meta: { title: '订单列表' }
      },
      {
        path: '/reports',
        name: 'reports',
        component: () => import('@/views/reports/reports.vue'),
        meta: { title: '数据报表' }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录' }
  }
]

const router = createRouter({
  history: createWebHashHistory(), // 路由模式
  routes
})

router.beforeEach((to, from) => {
  nprogress.start()
  if (to.meta.requiresAuth && !store.state.user) {
    // 此路由需要授权，请检查是否已登录
    // 如果没有，则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置，以便以后再来
      query: { redirect: to.fullPath }
    }
  }
})

router.afterEach(() => {
  nprogress.done()
})

export default router